package org.neuedu.vblogserver.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.neuedu.vblogserver.bean.Category;
import org.neuedu.vblogserver.bean.RespBean;
import org.neuedu.vblogserver.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryService {
    @Autowired
    CategoryMapper categoryMapper;
    public PageInfo getCategory(String serchKeyWord,int pageNum, int pageSize) {
        // 开启分页
        /*PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = categoryMapper.getCategory(serchKeyWord);
        PageInfo pageInfo = new PageInfo(categories);
        return pageInfo;*/
        PageHelper.startPage(pageNum,pageSize);
        List<Category> categories=categoryMapper.getCategory((serchKeyWord));
        PageInfo pageInfo =new PageInfo(categories);
        return pageInfo;
     }


    public RespBean addCategory(Category category) {

        category.setCreateTime(new Date());

        if(category.getCateName()==null||category.getCateName().trim().equals("")){
            return RespBean.error(500,"新增栏目名称不合规");
        }else {
            int i=categoryMapper.addCategory(category);
            if (i==0){
                return RespBean.error(500,"新增栏目失败");
            }else{
                return RespBean.success(200,"新增成功");
            }
        }
    }

    public RespBean deleteCategory(int id) {
        int count =categoryMapper.selectDelete(id);
            if (count==0){
                int i=categoryMapper.deleteCategory(id);
                if (i==0){
                    return RespBean.error(500,"删除失败");
                }else{
                    return RespBean.success(200,"删除成功");
                }
            }

        return RespBean.error(500,"栏目下有文章，不能删除");

    }

    public RespBean mulDeleteCategory(int[] ids) {

        for (int id : ids) {
            int count =categoryMapper.selectDelete(id);
            if (count!=0){
                return RespBean.error(500,"栏目下有文章，不能删除");
            }

        }
        int i=categoryMapper.mulDeleteCategory(ids);
        if (i==0){
            return RespBean.error(500,"删除失败");
        }else{
            return RespBean.success(200,"删除成功");
        }

    }

    public RespBean updateName(Category category) {

        if (category.getCateName()==null){
            return RespBean.error(500,"名称不符合要求");
        }else {
            int count = categoryMapper.updateName(category);
            if (count==0){
                return RespBean.error(500,"修改失败");
            }else {
                return RespBean.success(200,"修改成功");
            }
        }


    }
}
